import { NextRequest, NextResponse } from "next/server";
import { SqliteDatabase } from "@/lib/sqlite-database";

export async function POST(request: NextRequest) {
  try {
    console.log("开始重新导入CSV参数表数据...");
    
    const database = new SqliteDatabase();
    
    // 1. 清除现有的参数表数据
    console.log("清除现有参数表数据...");
    database.exec("DELETE FROM naming_parameters");
    database.exec("DELETE FROM position_parameters"); 
    database.exec("DELETE FROM base_parameters");
    console.log("现有参数表数据已清除");
    
    // 2. 获取所有设备
    console.log("获取设备数据...");
    const devices = database.getAllDevices();
    console.log(`找到 ${devices.length} 个设备`);
    
    // 3. 定义参数字段（基于原始CSV文件结构）
    const namingFields = [
      { name: "设计物资编码", dataType: "字符型", required: false },
      { name: "采购物资编码", dataType: "字符型", required: false },
      { name: "采购包号批次", dataType: "字符型", required: false },
      { name: "制造出厂编码", dataType: "字符型", required: false },
      { name: "物流编码", dataType: "字符型", required: false },
      { name: "仓储编码", dataType: "字符型", required: false },
      { name: "施工物资编码", dataType: "字符型", required: false },
      { name: "施工自编号", dataType: "字符型", required: false },
      { name: "运行资产编码", dataType: "字符型", required: false },
      { name: "石油天然气行业设备编码", dataType: "字符型", required: false },
      { name: "运行自编号", dataType: "字符型", required: false },
      { name: "流水码", dataType: "字符型", required: false }
    ];
    
    const positionFieldsC4 = [
      { name: "设计设备位号 / 管线号", dataType: "字符型", required: true },
      { name: "工厂地址", dataType: "字符型", required: false },
      { name: "工厂坐标", dataType: "字符型", required: false },
      { name: "物流地理信息", dataType: "字符型", required: false },
      { name: "物流坐标", dataType: "字符型", required: false },
      { name: "仓储地址", dataType: "字符型", required: false },
      { name: "仓储坐标", dataType: "字符型", required: false },
      { name: "施工设备位号", dataType: "字符型", required: false },
      { name: "施工 / 运行坐标", dataType: "字符型", required: false },
      { name: "运行设备位号", dataType: "字符型", required: false }
    ];
    
    const positionFieldsC6 = [
      { name: "设计设备位号/管线号", dataType: "字符型", required: true },
      { name: "工厂地址", dataType: "字符型", required: false },
      { name: "工厂坐标", dataType: "字符型", required: false },
      { name: "物流地理信息", dataType: "字符型", required: false },
      { name: "物流坐标", dataType: "字符型", required: false },
      { name: "仓储地址", dataType: "字符型", required: false },
      { name: "仓储坐标", dataType: "字符型", required: false },
      { name: "施工设备位号", dataType: "字符型", required: false },
      { name: "施工管线号", dataType: "字符型", required: false },
      { name: "施工/运行坐标", dataType: "字符型", required: false },
      { name: "运行设备位号", dataType: "字符型", required: false },
      { name: "运行管线号", dataType: "字符型", required: false }
    ];
    
    // 基础参数表映射（根据您的系统分析结果）
    const baseParamFieldsMap: Record<string, any[]> = {
      "表 C.18": [ // 离心泵基础参数表
        { name: "制造厂家", dataType: "字符型", unit: "", required: true },
        { name: "供货厂家", dataType: "字符型", unit: "", required: true },
        { name: "额定转速", dataType: "数值型", unit: "r/min", required: true },
        { name: "设备名称", dataType: "字符型", unit: "", required: true },
        { name: "装箱单号", dataType: "字符型", unit: "", required: false },
        { name: "出厂日期", dataType: "日期型", unit: "", required: false },
        { name: "规格", dataType: "字符型", unit: "", required: true },
        { name: "型号", dataType: "字符型", unit: "", required: true },
        { name: "额定功率", dataType: "数值型", unit: "kW", required: true },
        { name: "额定电流", dataType: "数值型", unit: "A", required: true }
      ],
      "表 C.27": [ // 转子泵基础参数表
        { name: "制造厂家", dataType: "字符型", unit: "", required: true },
        { name: "供货厂家", dataType: "字符型", unit: "", required: true },
        { name: "设备名称", dataType: "字符型", unit: "", required: true },
        { name: "装箱单号", dataType: "字符型", unit: "", required: false },
        { name: "出厂日期", dataType: "日期型", unit: "", required: false },
        { name: "规格", dataType: "字符型", unit: "", required: true },
        { name: "型号", dataType: "字符型", unit: "", required: true },
        { name: "额定转速", dataType: "数值型", unit: "r/min", required: true },
        { name: "额定功率", dataType: "数值型", unit: "kW", required: true },
        { name: "额定电流", dataType: "数值型", unit: "A", required: true }
      ],
      "表 C.81": [ // 圆筒形储罐基础参数表
        { name: "规格", dataType: "字符型", unit: "", required: true },
        { name: "型号", dataType: "字符型", unit: "", required: true },
        { name: "制造厂家", dataType: "字符型", unit: "", required: true },
        { name: "供货厂家", dataType: "字符型", unit: "", required: true },
        { name: "设计压力", dataType: "数值型", unit: "MPa", required: true },
        { name: "储罐名称", dataType: "字符型", unit: "", required: true },
        { name: "结构形式", dataType: "字符型", unit: "", required: true },
        { name: "储罐公称容积", dataType: "数值型", unit: "m³", required: true },
        { name: "储罐内直径", dataType: "数值型", unit: "m", required: true },
        { name: "罐壁高度", dataType: "数值型", unit: "m", required: true },
        { name: "材质规格", dataType: "字符型", unit: "", required: true },
        { name: "生产日期", dataType: "日期型", unit: "", required: false },
        { name: "出厂编号", dataType: "字符型", unit: "", required: false },
        { name: "设备代码", dataType: "字符型", unit: "", required: false },
        { name: "设计使用寿命", dataType: "数值型", unit: "年", required: false },
        { name: "设计单位", dataType: "字符型", unit: "", required: false },
        { name: "投运日期", dataType: "日期型", unit: "", required: false },
        { name: "储存介质", dataType: "字符型", unit: "", required: true },
        { name: "安装位置（场地）", dataType: "字符型", unit: "", required: false },
        { name: "注册登记证号（特种设备）", dataType: "字符型", unit: "", required: false },
        { name: "数量", dataType: "数值型", unit: "个", required: false },
        { name: "所属单位", dataType: "字符型", unit: "", required: false }
      ]
    };
    
    const defaultBaseFields = [
      { name: "规格", dataType: "字符型", unit: "", required: true },
      { name: "型号", dataType: "字符型", unit: "", required: true },
      { name: "制造厂家", dataType: "字符型", unit: "", required: true },
      { name: "供货厂家", dataType: "字符型", unit: "", required: true },
      { name: "设备名称", dataType: "字符型", unit: "", required: true }
    ];
    
    // 4. 为每个设备创建参数
    console.log("开始为设备创建参数...");
    let totalParams = 0;
    
    for (const device of devices) {
      let deviceParams = 0;
      
      // 创建命名参数（所有设备都使用表 C.2）
      for (const field of namingFields) {
        const sql = `INSERT INTO naming_parameters (device_id, parameter_name, parameter_value, data_type, is_required, created_at, updated_at) VALUES (${device.id}, '${field.name}', '', '${field.dataType}', ${field.required ? 1 : 0}, datetime('now'), datetime('now'))`;
        database.exec(sql);
        deviceParams++;
      }
      
      // 创建位置参数
      const positionFields = device.position_table_id === "表 C.6" ? positionFieldsC6 : positionFieldsC4;
      for (const field of positionFields) {
        const sql = `INSERT INTO position_parameters (device_id, parameter_name, parameter_value, data_type, is_required, created_at, updated_at) VALUES (${device.id}, '${field.name}', '', '${field.dataType}', ${field.required ? 1 : 0}, datetime('now'), datetime('now'))`;
        database.exec(sql);
        deviceParams++;
      }
      
      // 创建基础参数
      const baseFields = baseParamFieldsMap[device.base_params_table_id] || defaultBaseFields;
      for (const field of baseFields) {
        const sql = `INSERT INTO base_parameters (device_id, parameter_name, parameter_value, data_type, measurement_unit, is_required, created_at, updated_at) VALUES (${device.id}, '${field.name}', '', '${field.dataType}', '${field.unit || ''}', ${field.required ? 1 : 0}, datetime('now'), datetime('now'))`;
        database.exec(sql);
        deviceParams++;
      }
      
      totalParams += deviceParams;
      console.log(`设备 ${device.name} (${device.device_id}) 创建了 ${deviceParams} 个参数`);
    }
    
    console.log(`CSV参数表重新导入完成！总共创建了 ${totalParams} 个参数`);
    
    return NextResponse.json({
      success: true,
      message: `成功重新导入CSV参数表数据，总共为 ${devices.length} 个设备创建了 ${totalParams} 个参数`,
      data: {
        devicesProcessed: devices.length,
        totalParametersCreated: totalParams,
        parameterTypes: {
          naming: devices.length * namingFields.length,
          position: devices.filter(d => d.position_table_id === "表 C.6").length * positionFieldsC6.length + 
                   devices.filter(d => d.position_table_id !== "表 C.6").length * positionFieldsC4.length,
          base: totalParams - (devices.length * namingFields.length) - 
                (devices.filter(d => d.position_table_id === "表 C.6").length * positionFieldsC6.length + 
                 devices.filter(d => d.position_table_id !== "表 C.6").length * positionFieldsC4.length)
        },
        supportedBaseTables: Object.keys(baseParamFieldsMap).join(", "),
        tablesProcessed: {
          naming: "表 C.2 (NAM002 对象命名表)",
          position: "表 C.4 (LOC002 位置信息表) 和 表 C.6 (LOC004 位置信息表)",
          base: `${Object.keys(baseParamFieldsMap).length} 个基础参数表，其他使用默认5字段`
        }
      }
    });
    
  } catch (error) {
    console.error("重新导入CSV参数表时出错:", error);
    return NextResponse.json(
      { 
        success: false, 
        message: "重新导入CSV参数表过程中发生错误",
        error: error instanceof Error ? error.message : "未知错误"
      },
      { status: 500 }
    );
  }
} 